package models

import "github.com/astaxie/beego/orm"

type Menu struct {
	Id       int64  `json:"id"`
	Name     string `json:"name"`
	Fid      int64  `json:"fid"`
	Url      string `json:"url"`
	Sort     int    `json:"sort"`
	Hide     int8   `json:"hide"`
	Icon     string `json:"icon"`
	Level    int8   `json:"level"`
	ShowName string `json:"showName" orm:"-" form:"ShowName"`
}

func MenuList() ([]*Menu, int64) {
	sortorder := "Id"
	query := orm.NewOrm().QueryTable("tp_menu")
	data := make([]*Menu, 0)
	count, _ := query.Count()
	_, _ = query.OrderBy(sortorder).All(&data)
	list := menuList2TreeGrid(data)
	return list, count
}

func MenuSave(m *Menu) (int64, error) {
	o := orm.NewOrm()
	if m.Url != "" {
		m.Url = "admin/" + m.Url
	}
	if m.Id == 0 {
		id, err := o.Insert(m)
		if err != nil {
			return 0, err
		} else {
			m.Id = id
		}
	} else {
		if _, err := o.Update(m); err != nil {
			return 0, err
		}
	}
	return m.Id, nil
}

func MenuStatus(m *Menu) (int64, error) {
	o := orm.NewOrm()
	_, err := o.Update(m, "hide")
	return m.Id, err
}

func MenuDel(m *Menu) error {
	o := orm.NewOrm()
	_, err := o.QueryTable("tp_menu").Filter("id", m.Id).Delete()
	return err
}

func AuthAll() (arr []string, err error) {
	var maps []orm.Params
	query := orm.NewOrm().QueryTable("tp_menu")
	_, err = query.Filter("Hide", 0).Values(&maps, "Url")
	if err == nil {
		for _, item := range maps {
			arr = append(arr, item["Url"].(string))
		}
	}
	return arr, err
}

//构建树
func menuList2TreeGrid(list []*Menu) []*Menu {
	result := make([]*Menu, 0)
	for _, item := range list {
		if item.Fid == 0 {
			item.Level = 0
			item.ShowName = item.Name
			result = append(result, item)
			result = menuAddSons(item, list, result)
		}
	}
	return result
}

//构建子树
func menuAddSons(cur *Menu, list, result []*Menu) []*Menu {
	for _, item := range list {
		if item.Fid != 0 && item.Fid == cur.Id {
			item.Level = cur.Level + 1
			prefix := ""
			for a := 0; a < int(item.Level); a++ {
				prefix += "|---"
			}
			item.ShowName = prefix + item.Name
			result = append(result, item)
			result = menuAddSons(item, list, result)
		}
	}
	return result
}
